package com.example.teacherservice.entity;

import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import jakarta.persistence.*;
import lombok.Data;
import org.hibernate.annotations.CreationTimestamp;
import org.hibernate.annotations.UpdateTimestamp;

import java.time.LocalDateTime;
import java.util.List;

@Entity
@Table(name = "student")
@Data
@JsonIgnoreProperties({"hibernateLazyInitializer", "handler"})
public class Student {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    // 修改为只读字段，解决重复映射问题
    @Column(name = "user_id", insertable = false, updatable = false)
    private Long userId;

    @Column(name = "stu_name")
    private String stuName;

    @Column(name = "stu_study_time", nullable = false)
    private Long stuStudyTime = 0L;

    @Column(name = "stu_score")
    private Long stuScore = 100L;

    private String clock;

    @Column(name = "create_time", nullable = false)
    @CreationTimestamp
    private LocalDateTime createTime;

    @Column(name = "update_time", nullable = false)
    @UpdateTimestamp
    private LocalDateTime updateTime;

    @Column(name = "deleted", nullable = false)
    private Integer deleted = 0;


    // 添加安全的getter方法
    public User getSafeUser() {
        try {
            return user;
        } catch (EntityNotFoundException e) {
            return createDefaultUser();
        }
    }

    private User createDefaultUser() {
        User defaultUser = new User();
        defaultUser.setId(-1L);
        defaultUser.setUsername("unknown");
        defaultUser.setRole(1);
        return defaultUser;
    }

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "class_id", referencedColumnName = "id")  // 确保与数据库列名一致
    private Class classInfo;

    // 重写toString()避免递归和懒加载问题
    @Override
    public String toString() {
        return "Student{" +
                "id=" + id +
                ", stuName='" + stuName + '\'' +
                // 只包含基本字段，不包含关联实体
                '}';
    }

    // 对可能不存在的关联添加安全访问方法
    public String getSafeUserName() {
        try {
            return user != null ? user.getUsername() : "unknown";
        } catch (Exception e) {
            return "unknown";
        }
    }

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "user_id", nullable = true, foreignKey = @ForeignKey(ConstraintMode.NO_CONSTRAINT))
    private User user;

    // 添加安全访问方法
    public String getSafeUsername() {
        try {
            return user != null ? user.getUsername() : null;
        } catch (EntityNotFoundException e) {
            return null;
        }
    }

    public String getName() {
        return stuName;
    }

    @OneToMany(mappedBy = "student", cascade = CascadeType.ALL, orphanRemoval = true)
    @JsonIgnore
    private List<StuPractice> practices;
}